package com.wang.sort2;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: along
 * @Create: 2021/4/18 16:31
 * @Description:广度优先遍历BFS，利用队列QUEUE
 */
public class Demo11_LevelTraverseBT {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int v) {
            this.value = v;
        }
    }
    public static void level(Node head) {
        if(head == null) {
            return;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);//头节点入队
        while (!queue.isEmpty()) {
            Node cur = queue.poll();//出队一个元素
            System.out.println(cur.value);//并打印
            if(cur.left != null) {//先左后右向队列中添加，然后出队并打印
                queue.add(cur.left);
            }
            if(cur.right != null){
                queue.add(cur.right);
            }
        }
    }
    //for test
    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);

        level(head);
        System.out.println("========");
    }
}
